package cn.icanci.loopstack.amc.admin.dal.mongodb.mongo;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import cn.icanci.loopstack.amc.admin.dal.mongodb.daointerface.AppDAO;
import cn.icanci.loopstack.amc.admin.dal.mongodb.dataobject.AppDO;
import cn.icanci.loopstack.amc.common.model.PageList;

/**
 * @author icanci
 * @since 1.0 Created in 2023/01/15 12:24
 */
@Service("appDAO")
public class MongoAppDAO extends AbstractBaseDAO<AppDO> implements AppDAO {

    @Override
    public void insert(AppDO app) {
        super.insert(app);
        mongoTemplate.insert(app, COLLECTION_NAME);
    }

    @Override
    public void update(AppDO app) {
        super.update(app);
        mongoTemplate.save(app, COLLECTION_NAME);
    }

    @Override
    public List<AppDO> queryAll() {
        Criteria criteria = Criteria.where(AppColumn.env).is(DEFAULT_ENV);
        Query query = new Query(criteria);
        return mongoTemplate.find(query, COLLECTION_CLASS, COLLECTION_NAME);
    }

    @Override
    public PageList<AppDO> pageQuery(AppDO app, int pageNum, int pageSize) {
        Criteria criteria = Criteria.where(AppColumn.env).is(DEFAULT_ENV);

        if (StringUtils.isNotBlank(app.getAppName())) {
            // 不分区大小写查询，其中操作符"i"：表示不分区大小写
            criteria.and(AppColumn.appName).regex("^.*" + app.getAppName() + ".*$", "i");
        }

        if (StringUtils.isNotBlank(app.getTeamUuid())) {
            criteria.and(AppColumn.teamUuid).is(app.getTeamUuid());
        }

        Query query = new Query(criteria);
        query.with(Sort.by(Sort.Direction.DESC, AppColumn.createTime));

        return pageQuery(query, COLLECTION_CLASS, pageSize, pageNum, COLLECTION_NAME);
    }

    @Override
    public AppDO queryOneById(String _id) {
        Criteria criteria = Criteria.where(AppColumn._id).is(_id);
        criteria.and(AppColumn.env).is(DEFAULT_ENV);
        Query query = new Query(criteria);
        return mongoTemplate.findOne(query, COLLECTION_CLASS, COLLECTION_NAME);
    }

    @Override
    public AppDO queryByAppId(String appId) {
        Criteria criteria = Criteria.where(AppColumn.appId).is(appId);
        criteria.and(AppColumn.env).is(DEFAULT_ENV);
        Query query = new Query(criteria);
        return mongoTemplate.findOne(query, COLLECTION_CLASS, COLLECTION_NAME);
    }

    @Override
    public AppDO queryByAppName(String appName) {
        Criteria criteria = Criteria.where(AppColumn.appName).is(appName);
        criteria.and(AppColumn.env).is(DEFAULT_ENV);
        Query query = new Query(criteria);
        return mongoTemplate.findOne(query, COLLECTION_CLASS, COLLECTION_NAME);
    }
}
